package searchkeyword

import (
	"context"
	"strings"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateSearchKeywordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateSearchKeywordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateSearchKeywordLogic {
	return &UpdateSearchKeywordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateSearchKeywordLogic) UpdateSearchKeyword(req *types.UpdateSearchKeywordReq) (*types.BaseMsgResp, error) {
	if len(req.Ids) > 0 {
		res, err := l.svcCtx.BackendRpc.UpdateSearchKeyword(l.ctx, &backendclient.SearchKeywordInfo{
			Status: req.Status,
			Ids:    req.Ids,
		})
		if err != nil {
			return nil, err
		}

		return &types.BaseMsgResp{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
		}, nil
	}

	if req.Id == nil || *req.Id == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.StartedAt != nil && len(strings.TrimSpace(*req.StartedAt)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "searchkeyword.startedAtRequired"))
	}

	if req.EndedAt != nil && len(strings.TrimSpace(*req.EndedAt)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "searchkeyword.endedAtRequired"))
	}

	var objectId *uint64
	var objectType *uint32
	if req.LinkType != nil && *req.LinkType > 0 { // 相对路径，接收广告类型和广告ID
		objectType = req.ObjectType
		objectId = req.ObjectId
	}

	res, err := l.svcCtx.BackendRpc.UpdateSearchKeyword(l.ctx, &backendclient.SearchKeywordInfo{
		Id:         req.Id,
		Type:       req.Type,
		Title:      req.Title,
		LinkType:   req.LinkType,
		LinkUrl:    req.LinkUrl,
		ObjectType: objectType,
		ObjectId:   objectId,
		Status:     req.Status,
		Sort:       req.Sort,
		StartedAt:  req.StartedAt,
		EndedAt:    req.EndedAt,
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
